from flask import Flask, jsonify, abort, make_response, request, url_for



app = Flask(__name__)
	

tasks = [
    {
        'id': 1,
        'title': u'Buy groceries',
        'description': u'Milk, Cheese, Pizza, Fruit, Tylenol',
        'done': False
    },
    {
        'id': 2,
        'title': u'Learn Python',
        'description': u'Need to find a good Python tutorial on the web',
        'done': False
    }
]


#: Common method for uri
def make_public_task(task):

	new_task = {}
	for f in task.keys():
		if f == 'id':
			new_task['uri'] = url_for('get_tasks', task_id=task['id'], _external=True)
		else:
			new_task[f] = task[f]
	
	return new_task


#: Get all task
@app.route( '/todo/api/v1.0/tasks', methods=['GET'] )
def get_tasks():
	return jsonify( {'tasks': list(map(make_public_task, tasks))} )


#: Get by_ID
@app.route( '/todo/api/v1.0/tasks/<int:task_id>', methods=['GET'] )
def get_tasks_byID( task_id ):
	
	task = filter( lambda t: t['id'] == task_id, tasks )
	for t in task:
		if len(t) == 0:
			abort(404)

	return jsonify( {'tasks': tasks[task_id - 1]} )


#: 404
@app.errorhandler( 404 )
def not_found(error):
	return make_response( jsonify({'error':'Not Found'}) )


#: Create new task
@app.route('/todo/api/v1.0/tasks', methods=['POST'])
def create_task():
	
	if not request.json or not 'title' in request.json:
		abort(400)
	task = {
		'id': tasks[-1]['id'] + 1,
		'title': request.json['title'],
		'description': request.json.get('description', ""),
		'done': False
		}
	
	tasks.append(task)
	return jsonify( {'task': task} ), 201

	
#: Update task
@app.route('/todo/api/v1.0/tasks/<int:task_id>', methods=['PUT'])
def update_task(task_id):

	task = {}
	task_filter = filter(lambda t: t['id'] == task_id, tasks)
	for t in task_filter:
		task = t
		if len(t) == 0:
			abort(404)
	
	if not request.json:
		abort(400)
	
	if 'done' in request.json and type(request.json['done']) is not bool:
		abort(400)
	
	for t in task_filter:
		task.append[t]
	
	task['title'] = request.json.get('title', task['title'])
	task['description'] = request.json.get('description', task['description'])
	task['done'] = request.json.get('done', task['done'])
	
	return jsonify( {'task': task} )


#: Delete task
@app.route('/todo/api/v1.0/tasks/<int:task_id>', methods=['DELETE'])
def delete_task(task_id):
	
	task = {}
	task_filter = filter(lambda t: t['id'] == task_id, tasks)
	for t in task_filter:
		task = t
		if len(t) == 0:
			abort(404)
	
	tasks.pop( task['id'] - 1 )
	return jsonify({'result': True})


if __name__ == '__main__':
    app.run(debug=True)
